/*
 * @Descripttion:
 * @version:
 * @Author: lfzxs@qq.com
 * @Date: 2023-03-27 11:20:06
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2023-05-11 15:38:44
 */
package main

import (
	"fmt"
	"os"
	"time"

	"gitee.com/g_boot/webkit/middleware"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"golang.org/x/exp/slog"
)

func InitSlog() {
	opts := slog.HandlerOptions{
		Level: slog.LevelDebug,
	}
	slog.SetDefault(slog.New(opts.NewJSONHandler(os.Stdout)))
}

func MiddlewareCORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

func MakMatchMiddleware() ghttp.HandlerFunc {
	// enableOption :=  middleware.WithEnanle(true)
	excludeOption := middleware.WithExcludePath([]string{"/api/product/*"})
	mm := middleware.NewMatchMiddleware("test", nil, excludeOption)
	mm.Middleware = MiddlewareCORS
	return mm.Handle
}

func MakeMonitorMiddleware() ghttp.HandlerFunc {
	option := middleware.WithNotifys([]middleware.NotifyFun{DemoNotifys})
	result := middleware.NewMonitorMiddleware(option)
	return result.Handle
}

func MiddlewareAuthDomain() ghttp.HandlerFunc {

	enableOption := middleware.WithDomainEnanle(true)
	hostOption := middleware.WithDomainHost("*.histron.cn")
	dm := middleware.NewDomainMiddleware("domainAuth", enableOption, hostOption)

	return dm.Handle
}

func DemoNotifys(sender any, msg middleware.NotifyMap) {
	slog.Info(fmt.Sprintf("notify:%v", msg))
}

func main() {
	s := g.Server()
	InitSlog()

	// 例子
	s.Group("/api", func(group *ghttp.RouterGroup) {
		group.Middleware(MakMatchMiddleware())

		group.Middleware(MakeMonitorMiddleware())
		group.Middleware(MiddlewareAuthDomain())

		// 排除的路径
		group.ALL("/product/list", func(r *ghttp.Request) {
			r.Response.Writeln("product_list")
		})

		// 不排除的路径
		group.ALL("/user/list", func(r *ghttp.Request) {
			r.Response.Writeln("user_list")
			time.Sleep(1 * time.Second)
		})

		// 报错
		group.ALL("/user/error", func(r *ghttp.Request) {
			panic("error!!")
		})
	})

	s.SetPort(8199)
	s.Run()
}
